package com.zrf.testchatgpt.controller;

import cn.hutool.core.util.StrUtil;
import com.zrf.testchatgpt.entity.vo.AIVO;
import com.zrf.testchatgpt.entity.Detail;
import com.zrf.testchatgpt.entity.Users;
import com.zrf.testchatgpt.mapper.DetailMapper;
import com.zrf.testchatgpt.mapper.UsersMapper;
import com.zrf.testchatgpt.service.IConfigService;
import com.zrf.testchatgpt.service.impl.DetailServiceImpl;
import com.zrf.testchatgpt.util.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/ai")
@RequiresRoles(value = {"user","admin"},logical = Logical.OR)
//@RequiresRoles("user")
public class ChatgptController {

    @Autowired
    RedisCacheUtil redisCacheUtil;
    @Autowired
    IConfigService iSysConfigService;
    @Autowired
    DetailServiceImpl detailService;
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    DetailMapper detailMapper;
    @Autowired
    ChatModel chatModel;
    @Autowired
    pythonServiceUtil translateUtil;
    @PostMapping("/chat")
    public Result chat(@RequestBody AIVO aivo) {
        if (StrUtil.isBlank(aivo.getPrompt())) {
            return new Result("500","输入内容为空",null);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("content",aivo.getPrompt());
        map.put("role","user");
        return new Result("200","欢迎使用chatgpt",translateUtil.doPost(map));
    }
    @PostMapping("/chatBot")
    public Result chatBot(@RequestBody Users tbAnsweUser) {
        if (tbAnsweUser.getPrompt()==null){
            return Result.builder().code("500").msg("问题为空").build();
        }
        Detail detail=new Detail();
        detail.setUserId(tbAnsweUser.getId());
        detail.setAskquestion(tbAnsweUser.getPrompt());
        StringBuffer res=new StringBuffer();
        try {
            String getgpt = chatModel.getgpt(tbAnsweUser.getPrompt());
            res.append(getgpt);
        } catch (IOException e) {
            e.printStackTrace();
        }
        detail.setAnswerTitle(res.toString());
        detail.setAnswerContent(res.toString());
        detailService.insertDetail(detail);
        return Result.builder().code("200").msg("成功").data(res.toString()).build();
    }
    @GetMapping("/check")
    public Result chatBot() {
        return Result.builder().code("200").msg("成功").data(null).build();
    }
}
